<?php
namespace app\common\library\xilujob\resume;


use app\common\library\xilujob\ResumeLibrary;
use app\common\model\xilujob\EducationLevel;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\ResumeEducation;
use think\Model;

class Education extends BaseModule {

    protected $name = ResumeLibrary::MODULE_EDUCATION;

    public function onCreateResume(Resume $resume) {}

    /**
     * 获取所有字段的key
     * @return array
     */
    protected function keys() {
        return ['school_name','education_level_id','is_official','major','start','end'];
    }

    public function add($data) {
        $ret = parent::add($data);
        return $ret;
    }

    public function edit($data) {
        $ret = parent::edit($data);
        return $ret;
    }

    public function del($id) {
        $ret = parent::del($id);
        return $ret;
    }

    /**
     * 获取验证规则
     * @return array
     */
    protected function getRules() {
        return [
            'school_name' => 'require|length:1,20',
            'education_level_id' => function($value, $data) {
                $value = intval($value);
                if(!$value) {
                    return false;
                }
                return EducationLevel::where('id', $value)->count()>0;
            },
            'major' => 'require|length:1,20',
            'start|入学年份' => 'require|dateFormat:Y-m',
           // 'end|毕业年份' => ['require','regex'=>,'>:start'],
            'end' => function($value,$data){
                if(!$value){
                    return '毕业年份必须选择';
                }
                $reg = '/^(\d{4}-((0([1-9]))|(1(0|1|2))))|(至今)$/';
                if(!preg_match($reg,$value)){
                    return '毕业年份错误';
                }

                if($value !='至今' && $value<=$data['start']){
                    return '毕业年份必须大于入学年份';
                }
                return true;
            },
        ];
    }

    protected function check_start($value, $rule, $data){

    }

    /**
     * 获得Model实例
     * @return Model
     */
    protected function getModel() {
        return new ResumeEducation();
    }

    /**
     * 更新简历的最高学历
     */
    protected function updateHighestEducation() {
        $education = ResumeEducation::alias('edu')->join('EducationLevel level','edu.education_level_id=level.id')
            ->where('resume_id', $this->resume->id)
            ->order('level.weigh','desc')
            ->limit(0,1)
            ->find();
        $highestLevelId = $education ? $education->education_level_id : 0;
        $this->resume->save(['highest_education_level_id'=>$highestLevelId]);
    }

    /**
     * @return array score: 当前分数， max: 满分
     */
    public function getCompleteScore() {
        $max = 20;
        $count = ResumeEducation::where('resume_id',$this->resume->id)->count();
        $score = $count>0 ? 20 : 0;
        return ['score'=>$score, 'max'=>$max];
    }

}